<template>
  <AdminLayout>
    <el-card class="add-course-card">
      <template #header>
        <div class="card-header">
          <h2>添加课程</h2>
        </div>
      </template>
      
      <el-form 
        :model="courseForm" 
        :rules="rules" 
        ref="courseFormRef" 
        label-width="120px"
        :disabled="submitting"
        class="course-form"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input 
            v-model="courseForm.courseName" 
            placeholder="请输入课程名称" 
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="课程编码" prop="courseCode">
          <el-input 
            v-model="courseForm.courseCode" 
            placeholder="请输入课程编码" 
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input-number 
            v-model="courseForm.credit" 
            :min="0.5" 
            :max="10"
            :step="0.5"
            placeholder="请输入学分"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input 
            v-model="courseForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入课程描述（选填）" 
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <div class="form-actions">
            <el-button type="primary" @click="handleSubmit" :loading="submitting">提交</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>
  </AdminLayout>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { useRouter } from 'vue-router'
import { postJson } from '../../utils/api'
import AdminLayout from '../../components/admin/AdminLayout.vue'

const router = useRouter()

// 表单引用
const courseFormRef = ref<InstanceType<typeof ElForm> | null>(null)

// 表单数据
const courseForm = reactive({
  courseName: '',
  courseCode: '',
  credit: 1,
  description: ''
})

// 提交状态
const submitting = ref(false)

// 表单验证规则
const rules = reactive({
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 1, max: 50, message: '课程名称长度在 1 到 50 个字符之间', trigger: 'blur' }
  ],
  courseCode: [
    { required: true, message: '请输入课程编码', trigger: 'blur' },
    { min: 1, max: 20, message: '课程编码长度在 1 到 20 个字符之间', trigger: 'blur' }
  ],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    {
      validator: (rule: any, value: number, callback: Function) => {
        if (value < 0.5 || value > 10) {
          callback(new Error('学分必须在0.5到10之间'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  description: [
    { 
      required: false, 
      max: 200, 
      message: '课程描述长度不能超过 200 个字符', 
      trigger: 'blur'
    }
  ]
})

// 提交表单
const handleSubmit = async () => {
  if (!courseFormRef.value) return
  
  try {
    // 表单验证
    await courseFormRef.value.validate()
    
    // 设置提交状态
    submitting.value = true
    
    // 准备请求数据
    const submitData = {
      courseName: courseForm.courseName,
      courseCode: courseForm.courseCode,
      credit: courseForm.credit,
      description: courseForm.description || ''
    }
    
    // 调用后端API添加课程
    const result = await postJson('/course/add', submitData)
    
    // 根据API返回结果处理
    if (result.code === 200) {
      ElMessage.success(result.msg || '添加课程成功')
      // 返回课程列表页面
      router.push('/admin/course/list')
    } else {
      ElMessage.error(result.msg || '添加失败')
    }
  } catch (error) {
    if (error !== false) { // 如果不是表单验证失败
      console.error('添加课程失败:', error)
      ElMessage.error('网络错误，请检查后端服务是否正常运行')
    }
  } finally {
    submitting.value = false
  }
}

// 取消操作
const handleCancel = () => {
  // 返回课程列表页面
  router.push('/admin/course/list')
}
</script>

<style scoped>
.add-course-card {
  max-width: 600px;
  margin: 0 auto;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.course-form {
  padding: 20px 0;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.el-form-item__content) {
  min-width: 300px;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
}
</style>